// import { dataList } from './mock'
const { dataList } = require('./mock')
const bodyParser = require('body-parser')
const users = {
  admin: {
    id: 1,
    avatar: 'https://www.robohash.org/1',
  },
  devin: {
    id: 2,
    avatar: 'https://www.robohash.org/2',
  },
}
// console.log('dataList:', dataList)
module.exports = (app) => {
  app.use(bodyParser.json())
  app.post('/api/login', (req, res) => {
    const { username, password } = req.body
    res.json({
      code: 0,
      msg: 'success',
      data: {
        userInfo: users[username],
        token: `${users[username]?.id}_${username}`,
      },
    })
  })
  // 新闻标题接口

  app.get('/api/header', (req, res) => {
    // let brr = []
    // dataList.arr.forEach((item) => {
    //   brr.push(item.type)
    // })

    const brr = dataList.arr.reduce((arr, item) => {
      arr.push(item.type)
      return arr
    }, [])

    res.json({ code: 0, msg: 'success', data: brr })
  })

  // 新闻列表接口
  app.get('/api/news', (req, res) => {
    // 1. 接收参数 2. 处理参数 3. 返回结果
    const { type } = req.query
    res.json({ code: 0, msg: 'success', data: dataList.arr.filter((item) => item.type === type) })
  })
  // 上拉加载接口
  app.get('/api/load', (req, res) => {
    const { page = 1, size = 10, type = 'headline' } = req.query
    // res.json({ code: 0, msg: 'success', data: dataList.arr.slice((page - 1) * size, page * size) })

    /**page 1 size 5
     * i < 0 -- 5
     *  i >= page-1 * size 0
     * i< page*size 5
     * 0-4
     */

    let brr = dataList.arr.find((v) => v.type === type)
    res.json({
      code: 0,
      msg: 'success',
      data: brr.children.filter((v, i) => i >= (page - 1) * size && i < page * size),
    })
  })
}
